<template>
  <div class="index">
    <!-- 搜索框 -->
    <navBar>
      <template #left>
        <i class="van-icon van-icon-wap-nav" @click="showChannels = true"></i>
      </template>
      <template #center>
        <van-search
          :v-model="searchValue"
          placeholder="请输入搜索关键词"
          shape="round"
          @click="$router.push('/search')"
        />
      </template>
      <template #right>
        <i
          class="van-icon van-icon-search"
          @click="$router.push('/search')"
        ></i>
      </template>
    </navBar>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <!-- 上拉加载 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="content">
          <!-- 标签栏 -->
          <van-tabs
            title-active-color="#3194ff"
            title-inactive-color="#7d7e90"
            color="#3194ff"
            @click="onClick"
            v-model="index"
          >
            <van-tab
              v-for="(item, index) in myChannelsList"
              :title="item.name"
              :key="index"
            >
              <div
                class="items"
                v-for="(item, index) in articlesList"
                :key="index"
              >
                <div class="top" @click="$router.push(`/detail/${artId}`)">
                  <div class="title">{{ item.title }}</div>
                  <img
                    :src="item.cover.images"
                    alt=""
                    v-if="item.cover.type > 0"
                  />
                </div>
                <div class="bottom">
                  <div class="left">
                    <span>{{ item.aut_name }}</span>
                    <span>{{ item.comm_count }}评论</span>
                    <span>{{ item.pubdate | dayjsFilter }}</span>
                  </div>
                  <div class="right">
                    <i class="van-icon van-icon-cross" @click="del(index)"></i>
                  </div>
                </div>
              </div>
            </van-tab>
            <div class="show" v-if="show"></div>
            <!-- 文章区域 -->
          </van-tabs>
        </div>
      </van-list>
    </van-pull-refresh>
    <!-- 弹出层 -->
    <van-popup v-model="showPop">
      <van-cell-group>
        <van-cell title="不感兴趣" icon="failure" @click="dislike(index)" />
        <van-cell
          title="反馈垃圾内容"
          icon="warning-o"
          is-link
          @click="showFeedbackPop"
        />
        <van-cell title="拉黑作者" icon="delete-o" @click="black" />
      </van-cell-group>
    </van-popup>
    <!-- 反馈垃圾内容弹出层 -->
    <van-popup v-model="showFeedback">
      <van-cell icon="arrow-left" @click="backPop" />
      <van-cell
        :title="item"
        v-for="(item, index) in typeArr"
        :key="index"
        @click="report(index)"
      />
    </van-popup>
    <!-- 频道弹出层 -->
    <van-popup
      v-model="showChannels"
      position="left"
      :style="{ height: '100%' }"
    >
      <van-cell-group :border="false">
        <div class="channelContent">
          <div class="cross" @click="showChannels = false">
            <i class="van-icon van-icon-cross"></i>
          </div>
          <div class="title">
            <span>我的频道</span>
            <span class="edit" @click="edit">{{ editOrDone }}</span>
          </div>
          <div class="text">
            <span
              v-for="(item, index) in myChannelsList"
              :key="index"
              @click="changeTab(index)"
            >
              {{ item.name }}
              <i
                class="delete van-icon van-icon-clear"
                v-if="editOrDone === '完成' && index !== 0"
                @click.stop="clear(item, index)"
              ></i>
            </span>
          </div>
          <div class="title">
            <span class="channel">频道推荐</span>
          </div>
          <div class="text">
            <span
              v-for="(item, index) in recomChannelsList"
              :key="index"
              @click="add(item, index)"
            >
              + {{ item.name }}
            </span>
          </div>
        </div>
      </van-cell-group>
    </van-popup>
    <back-top />
  </div>
</template>

<script>
import navBar from '../../../components/navBar'
import { mapMutations } from 'vuex'
import {
  getMyChannelsApi,
  getRecomChannelsApi,
  getArticlesApi,
  getDislikesApi,
  getReportsApi,
  editChannelsApi,
  deleteChannelsApi,
  getBlackApi
} from '../../../api/articles'
export default {
  name: 'myindex',
  components: {
    navBar
  },
  data () {
    return {
      // 搜索框的值
      searchValue: '',
      // 下拉刷新的状态
      refreshing: false,
      // 上拉加载的状态
      loading: false,
      // 是否加载完成
      finished: false,
      // 我的频道列表
      myChannelsList: [],
      // 推荐频道列表
      recomChannelsList: [],
      // 频道文章列表
      articlesList: [],
      index: 0,
      // 弹出层状态
      showPop: false,
      // 反馈内容弹出层
      showFeedback: false,
      // 文章列表的下标
      currIndex: 0,
      // 文章id
      artId: 0,
      // 举报类型,
      show: false,
      typeArr: [
        '标题夸张',
        '低俗色情',
        '错别字多',
        '旧闻重复',
        '广告软文',
        '内容不实',
        '涉嫌违法犯罪',
        '侵权',
        '其他问题'
      ],
      // 频道弹出层
      showChannels: false,
      editOrDone: '编辑',
      // 用户id
      userId: 0,
      // 阅读时长
      read: ''
    }
  },
  created () {
    window.onscroll = function () {
      // console.log(document.documentElement.scrollTop)
    }

    // this.myChannelsList = this.userInfo.myChannel ? this.userInfo.myChannel : []
    // this.getRecomChannels()
  },
  activated () {},
  methods: {
    ...mapMutations(['setUserInfo']),
    // 上拉加载
    async onLoad () {
      if (this.articlesList.length > 20) {
        this.finished = true
        return
      }
      // if (!localGet('myChannel')) {
      //   const res = await getMyChannelsApi()
      //   console.log(res)
      //   localSet('myChannel', res.data.channels)
      //   this.setUserInfo('myChannel', res.data.channels)
      // }
      // 获取我的频道列表
      if (this.myChannelsList.length === 0) {
        const res = await getMyChannelsApi()
        this.myChannelsList = res.data.channels
      }

      if (this.recomChannelsList.length === 0) {
        const nameList = this.myChannelsList.map(i => {
          return i.name
        })
        // 获取推荐频道列表
        const res = await getRecomChannelsApi()
        // console.log(res)
        res.data.channels.forEach(item => {
          if (!nameList.includes(item.name)) {
            this.recomChannelsList.push(item)
          }
        })
      }
      this.getArticles('load')
    },
    // 下拉刷新
    onRefresh () {
      this.getArticles('refresh')
      this.refreshing = false
    },
    // 获取频道文章列表
    async getArticles (text) {
      const res = await getArticlesApi({
        channel_id: this.myChannelsList[this.index].id,
        with_top: 0,
        timestamp: Date.now()
      })
      console.log(res)

      if (res.data.results.length === 0) {
        this.articlesList = []
        this.show = true
        this.finished = true
        return
      }

      this.show = false
      // console.log(res)

      this.articlesList =
        text === 'load'
          ? [...res.data.results, ...this.articlesList]
          : res.data.results
      this.artId = this.articlesList[this.index].art_id
      this.userId = this.articlesList[this.index].aut_id
      this.read = this.articlesList[this.index].trace.read
      this.setUserInfo({ read: this.read })
      // console.log(this.read)
      this.loading = false
    },
    // 频道列表tab栏切换
    onClick (index) {
      this.finished = false
      this.index = index
      // console.log(index)
      this.getArticles()
    },
    del (index) {
      this.showPop = true
      this.currIndex = index
      // console.log(this.currIndex);
    },
    // 显示反馈垃圾内容弹出层
    showFeedbackPop () {
      this.showFeedback = true
      this.showPop = false
    },
    // 返回弹出层
    backPop () {
      this.showFeedback = false
      this.showPop = true
    },
    // 不感兴趣
    async dislike () {
      const res = await getDislikesApi({
        target: this.artId
      })
      console.log(res)
      this.$toast.success('操作成功')
      this.articlesList.splice(this.currIndex, 1)
      this.showPop = false
    },
    // 反馈垃圾内容
    async report (index) {
      try {
        const res = await getReportsApi({
          target: this.artId,
          type: index
        })
        console.log(res)
        this.showFeedback = false
        this.$toast.success('举报成功')
        this.articlesList.splice(this.currIndex, 1)
      } catch (error) {
        this.showFeedback = false
        this.$toast.fail('已举报过该文章')
        this.articlesList.splice(this.currIndex, 1)
        console.log(error)
      }
    },
    // 拉黑作者
    async black () {
      const res = await getBlackApi({
        target: this.userId
      })
      console.log(res.data.target)
      this.showPop = false
      this.$toast.success('拉黑成功')
      this.articlesList.splice(this.currIndex, 1)
    },
    // 频道编辑
    edit () {
      if (this.editOrDone === '编辑') {
        this.editOrDone = '完成'
      } else {
        this.editOrDone = '编辑'
      }
    },
    // 添加频道
    async add (item, index) {
      this.recomChannelsList.splice(index, 1)
      this.myChannelsList.push(item)
      // localSet('myChannel', this.myChannelsList)
      // this.setUserInfo('myChannel', this.myChannelsList)
      this.myChannelsList.forEach(async (item, index) => {
        item.seq = index + 1
      })
      const data = this.myChannelsList.slice(1).map(item => {
        return { id: item.id, seq: item.seq }
      })
      const res = await editChannelsApi({
        channels: data
      })

      console.log(res)
    },
    // 移除频道
    async clear (item, index) {
      try {
        this.myChannelsList.splice(index, 1)
        this.recomChannelsList.unshift(item)
        // localSet('myChannel', this.myChannelsList)
        // this.setUserInfo('myChannel', this.myChannelsList)
        const res = await deleteChannelsApi({
          channels: item.id
        })
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    // tab切换
    changeTab (index) {
      this.showChannels = false
      this.index = index
      this.getArticles()
    }
  },
  // 监控频道弹出层
  watch: {
    showChannels (newValue) {
      if (!newValue) {
        this.editOrDone = '编辑'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.index {
  margin-top: 46px;
  margin-bottom: 50px;
  /deep/ .van-search {
    background-color: transparent !important;
  }
  /deep/ .left {
    margin-top: 6px;
  }
  /deep/ .right {
    margin-top: 6px;
  }
  .content {
    position: relative;
    overflow: hidden;
    /deep/.van-tabs--line .van-tabs__wrap {
      border-bottom: 1px solid #ebedf0;
    }
    .items {
      padding: 8px 12px;
      border-bottom: 1px solid #ebedf0;
      .top {
        display: flex;
        justify-content: space-between;
        .title {
          font-size: 16px;
          color: #3a3a3a;
          margin-right: 10px;
        }
        img {
          width: 116px;
          height: 73px;
          border-radius: 2px;
        }
      }
      .bottom {
        display: flex;
        font-size: 12px;
        color: #999;
        padding-top: 8px;
        .left {
          flex: 1;
          span {
            margin-right: 10px;
          }
        }
        .right {
          border: 0.5px solid #edeff3;
          padding: 0 5px;
          height: 14px;
          line-height: 14px;
          border-radius: 2px;
          color: #cfcfcf;
        }
      }
    }
  }
  /deep/ .van-popup {
    width: 85%;
    z-index: 10000 !important;
    .channelContent {
      margin: 15px 10px;
      .cross {
        font-size: 30px;
      }
      .title {
        display: flex;
        justify-content: space-between;
        font-size: 16px;
        margin: 8px 0;
        .edit {
          font-size: 14px;
          color: #f85a5a;
          padding: 0 5px;
          border: 1px solid #f85a5a;
          border-radius: 14px;
        }
        .channel {
          margin-top: 30px;
        }
      }
      .text {
        display: flex;
        flex-wrap: wrap;
        margin-top: 18px;
        span {
          position: relative;
          padding: 6px 10px;
          margin: 5px 0;
          margin-left: 12px;
          font-size: 14px;
          color: #fff;
          background-color: #a7a5a5;
          border-radius: 4px;
          .delete {
            position: absolute;
            right: -5px;
            top: -5px;
            color: #cdcdcd;
            font-size: 14px;
          }
        }
      }
    }
  }
}
.show {
  text-align: center;
  position: absolute;
  height: 400px;
  width: 100%;
  opacity: 0;
  top: 46px;
  left: 0;
  width: 100%;
  z-index: 10000000;
}
</style>
